package com.jshoperxms.controller.mall.backstage.community;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.FaqEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.CommunityCircleArticleT;
import com.jshoperxms.service.CommunityCircleArticleTService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.*;

/**
 * Created by sdywcd on 16/12/4.
 * Des:
 */
@Controller
@RequestMapping("/mall/communitycirclearticle")
public class CommunityCircleArticleTController extends BaseTController implements IBaseCtrl<CommunityCircleArticleT> {

    @Resource
    private CommunityCircleArticleTService communityCircleArticleTService;

    private Map<String,Object> responsedata=new HashMap<>();



    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody CommunityCircleArticleT rq) throws ParseException {
        if(StringUtils.isBlank(rq.getCtitle())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            CommunityCircleArticleT bean=new CommunityCircleArticleT();
            bean.setId(this.serial.Serialid(SerialKeys.COMMUNITYCIRCLEARTICLET));
            bean.setCai(0);
            bean.setReplycount(0);
            bean.setCommunitycircleid(rq.getCommunitycircleid());
            bean.setCommunitycirclename(rq.getCommunitycirclename());
            bean.setContentvalue(rq.getContentvalue());
            bean.setCreatetime(DateTools.getSystemTimeBi());
            bean.setCreatorid(BaseTools.getAdminCreateId());
            bean.setCtitle(rq.getCtitle());
            bean.setHeadpath(StaticKey.EMPTY);
            List<ImgFileBean>imgs= GsonJson.parseJsonToData(rq.getImgs(),ImgFileBean.class);
            List<String>imgsstr=new ArrayList<>();
            List<String>simgsstr=new ArrayList<>();
            for(ImgFileBean img:imgs){
                imgsstr.add(img.getNormalfilepath());
                simgsstr.add(img.getCompressfilepath());
            }
            bean.setImgs(StringUtils.join(imgsstr,TagWords.SPLITDOT));
            bean.setSimgs(StringUtils.join(simgsstr,TagWords.SPLITDOT));
            bean.setNick("系统");
            bean.setReviewed(FaqEnums.FaqReviewed.PASS.getState());
            bean.setReviewedtime(BigInteger.valueOf(1L));
            bean.setSign(SerialKeys.COMMUNITYCIRCLEARTICLET+TagWords.HR+DateTools.getSystemTimeBi());
            bean.setSort(1);
            bean.setStatus(rq.getStatus());
            bean.setUpdatetime(DateTools.getSystemTimeBi());
            bean.setVersiont(1);
            bean.setZan(0);
            this.communityCircleArticleTService.save(bean);
            responsedata.put(TagWords.SUCCESS, true);
            responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody CommunityCircleArticleT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            CommunityCircleArticleT bean=this.communityCircleArticleTService.findByPK(CommunityCircleArticleT.class,rq.getId());
            if(bean!=null){
                List<ImgFileBean>ifbs=new LinkedList<>();
                String imgs[]=StringUtils.split(bean.getImgs(),TagWords.SPLITDOT);
                String simgs[]=StringUtils.split(bean.getSimgs(),TagWords.SPLITDOT);
                if(imgs!=null&&imgs.length>0){
                    for(int i=0;i<imgs.length;i++){
                        ImgFileBean ifbi=new ImgFileBean();
                        ifbi.setNormalfilepath(imgs[i]);
                        if(simgs.length>0){
                            ifbi.setCompressfilepath(simgs[i]);
                        }else{
                            ifbi.setCompressfilepath(StaticKey.EMPTY);
                        }
                        ifbi.setBasepath(StaticKey.EMPTY);
                        ifbs.add(ifbi);
                    }
                }
                responsedata.put(TagWords.IFBS,ifbs);
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,TagWords.INVALIDDATA);
            }
        }
        return Response.success(responsedata);

    }

    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody CommunityCircleArticleT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(),TagWords.SPLITDOT);
            for(String s:ids){
                CommunityCircleArticleT bean=this.communityCircleArticleTService.findByPK(CommunityCircleArticleT.class,s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.communityCircleArticleTService.update(bean);
                }
            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody CommunityCircleArticleT rq) throws ParseException {
        if(StringUtils.isBlank(rq.getCtitle())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            CommunityCircleArticleT bean=this.communityCircleArticleTService.findByPK(CommunityCircleArticleT.class,rq.getId());
            if(bean!=null){
                bean.setCommunitycircleid(rq.getCommunitycircleid());
                bean.setCommunitycirclename(rq.getCommunitycirclename());
                bean.setContentvalue(rq.getContentvalue());
                bean.setCtitle(rq.getCtitle());
                List<ImgFileBean>imgs= GsonJson.parseJsonToData(rq.getImgs(),ImgFileBean.class);
                List<String>imgsstr=new ArrayList<>();
                List<String>simgsstr=new ArrayList<>();
                for(ImgFileBean img:imgs){
                    imgsstr.add(img.getNormalfilepath());
                    simgsstr.add(img.getCompressfilepath());
                }
                bean.setImgs(StringUtils.join(imgsstr,TagWords.SPLITDOT));
                bean.setSimgs(StringUtils.join(simgsstr,TagWords.SPLITDOT));
                bean.setStatus(rq.getStatus());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                this.communityCircleArticleTService.update(bean);
            }
            responsedata.put(TagWords.SUCCESS, true);
            responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }



    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion= Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("ctitle",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("ctitle",search,MatchMode.ANYWHERE));
            }
            int records=this.communityCircleArticleTService.count(CommunityCircleArticleT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<CommunityCircleArticleT> list = this.communityCircleArticleTService.findByCriteriaByPage(
                    CommunityCircleArticleT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageList(list);

        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        criterion=Restrictions.and(criterion).add(Restrictions.like("ctitle",search,MatchMode.ANYWHERE));
        int records=this.communityCircleArticleTService.count(CommunityCircleArticleT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<CommunityCircleArticleT> list = this.communityCircleArticleTService.findByCriteriaByPage(
                CommunityCircleArticleT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.communityCircleArticleTService.count(CommunityCircleArticleT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order= BaseTools.orderByParam("ctitle",ordervalue,ordertype);
        List<CommunityCircleArticleT> list = this.communityCircleArticleTService.findByCriteriaByPage(
                CommunityCircleArticleT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<CommunityCircleArticleT> list) {
        List<Map<String,Object>>data=new ArrayList<>();
        for(CommunityCircleArticleT bean:list){
            Map<String,Object>cellMap=new HashMap<>();
            cellMap.put("id",bean.getId());
            cellMap.put("ctitle",bean.getCtitle());
            cellMap.put("communitycirclename",bean.getCommunitycirclename());
            cellMap.put("reviewed", FaqEnums.FaqReviewed.getName(bean.getReviewed()));
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA,data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
